import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { DataUri, Graph } from '@antv/x6';
import { Store } from '@ngrx/store';

import { GraphService } from '../util/graph.service';

@Component({
  selector: 'app-menu-tool',
  templateUrl: './menu-tool.component.html',
  styleUrls: ['./menu-tool.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MenuToolComponent implements OnInit {

  canRedo = false;
  canUndo = false;
  miniMapStatus = true;

  private history!: Graph.HistoryManager;
  private graph!: Graph;

  constructor(
    private cd: ChangeDetectorRef,
    private graphService: GraphService,
  ) {
    this.graphService.graph$.subscribe((graph) => {
      if (graph) {
        this.history = graph.history;
        this.graph = graph;
      }
    });
  }

  ngOnInit(): void {
    this.history.on('change', () => {
      this.canRedo = this.history.canRedo();
      this.canUndo = this.history.canUndo();
      this.cd.markForCheck();
    });

  }

  undo() {
    this.history.undo();
  }

  redo() {
    this.history.redo();
  }

  center() {
    this.graph.center();
  }

  centerContent() {
    this.graph.centerContent();
  }

  clear() {
    this.graph.clearCells();
  }

  minMap() {
    this.miniMapStatus = !this.miniMapStatus;
    this.graphService.minMapBtn$.emit(this.miniMapStatus);
  }

  export(type?: 'png') {
    if (type) {
      this.graph.toPNG((dataUri: string) => {
        DataUri.downloadDataUri(dataUri, 'chart.png');
      }, {
        padding: {
          top: 20,
          right: 30,
          bottom: 40,
          left: 50,
        },
      });
      return;
    }
    this.graph.toSVG((dataUri: string) => {
      DataUri.downloadDataUri(DataUri.svgToDataUrl(dataUri), 'chart.svg');
    });
  }

  exportJson() {
    this.graphService.btnJson$.emit(true);
  }

  importJson() {
    this.graphService.btnJson$.emit(false);
  }
}
